/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
	//owner.server = "http://192.168.3.15:8001";
	owner.server = "http://192.168.3.11:8001";
	//owner.server = "http://cc.chinahdfe.com";
	owner.api = owner.server + "/app.ashx?type=";
	owner.isNet = true;

	owner.getSiteUrl = function() {
		return owner.api.replace("/app.ashx?type=", "");
	};

	owner.onNetChange = function() {
		var nt = plus.networkinfo.getCurrentType();
		switch(nt) {
			case plus.networkinfo.CONNECTION_ETHERNET:
			case plus.networkinfo.CONNECTION_WIFI:
				console.log("Switch to Wifi networks!");
				break;
			case plus.networkinfo.CONNECTION_CELL2G:
			case plus.networkinfo.CONNECTION_CELL3G:
			case plus.networkinfo.CONNECTION_CELL4G:
				console.log("Switch to Cellular networks!");
				break;
			default:
				owner.isNet = false;
				plus.nativeUI.toast("网络不可用");
				break;
		}
	};

	owner.post = function(url, data, success, isCache) {
		if(url == "") {
			console.log("ajax post url is null");
			return false;
		}

		data = data || {};
		url = owner.api + url;

		if(!data.MemberAccount) {
			data.MemberAccount = owner.account();
		}

		console.log(url);
		console.log(JSON.stringify(data));

		mui.ajax(url, {
			data: data,
			dataType: "json", //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				mui.hideLoading();
				if(isCache) {
					localStorage.setItem('$Cache' + url, JSON.stringify(data));
					console.log(localStorage.getItem('$Cache' + url));
				}
				success(data);
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(JSON.stringify(xhr));
				console.log(type + " error：" + errorThrown);
				mui.hideLoading();
				switch(type) {
					case "error":
						mui.toast("系统错误：" + errorThrown);
						break;
					case "timeout":
					case "abort":
					case "parsererror":
						//plus.nativeUI.toast(type + " error：" + errorThrown);
						//break;
					case "null":
					default:
						if(isCache) {
							success(JSON.parse(localStorage.getItem('$Cache' + url)));
						}
						mui.toast("网络不可用");
						break;
				}
			}
		});
	};

	owner.openLogin = function(type) {
		var $wvlogin = plus.webview.getWebviewById("login.html");
		if(type) $wvlogin.evalJS("setShowType(" + type + ")")
		$wvlogin.show("pop-in");
	};

	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		mui.showLoading();

		owner.post("Login", loginInfo, function(data) {
			if(data.isSuccess) {
				console.log(JSON.stringify(data));

				owner.loginCallback(data, callback);
			} else {
				callback(data);
			}
		});
	};
	
	owner.loginCallback = function (data, callback) {
		owner.setUser(data.data);
		owner.getBankCardData();
		
		owner.getBankNameData();
		
		owner.setMessageBadge(data.data.User.UnreadMessage > 0)
		
		owner.createState(data.data.User.MemberAccount, callback);
	}

	owner.setMessageBadge = function(enabled) {
		var wv = plus.webview.getLaunchWebview();
		if(wv) {
			wv.evalJS("setMessageBadge(" + enabled + ")");
		}
	}

	/**
	 * 退出登录 
	 */
	owner.logout = function() {
		owner.setState({});
		owner.setUser({});
		owner.setBankCard([]);
		owner.setBankName([]);

		owner.openLogin(1);
	};

	/**
	 * 账号多次登录 
	 */
	owner.otherLogin = function() {
		plus.nativeUI.alert("您的账号已在其它手机上登录，如非本人操作，请登录会员系统修改账号密码。");
		owner.logout();
	};

	owner.getMyBankCard = function(item) {
		return item.BankName + " (" + (item.CardNo.substr(item.CardNo.length - 4)) + ")";
	};

	/*
	 * 获取银行卡
	 * */
	owner.getBankCardSelect = function(type) {
		var data = owner.getBankCard();
		var dataSelect = [{
			value: 0,
			text: "添加新卡"
		}];

		mui.each(data, function(i, v) {
			if(v.Type == type) {
				dataSelect.push({
					value: v.ID,
					text: owner.getMyBankCard(v)
				});
			}
		});

		return dataSelect;
	};

	/**
	 * 获取银行卡
	 **/
	owner.getBankCard = function() {
		var text = localStorage.getItem('$BankCard') || "[]";
		return JSON.parse(text);
	};

	/**
	 * 设置银行卡
	 **/
	owner.setBankCard = function(data) {
		data = data || [];
		localStorage.setItem('$BankCard', JSON.stringify(data));
	};

	owner.getBankCardData = function(callback) {
		owner.post("GetBankCardAll", {}, function(data) {
			console.log(JSON.stringify(data));
			owner.setBankCard(data.data);
			if(callback)
				callback(data.data);
		});
	};
	
	owner.getBankText = function (code) {
		return owner.getBankName(code).Name;
	}
	
	owner.getBankAbbr = function (code) {
		return owner.getBankName(code).NameAbbr;
	}

	owner.getBankName = function(code) {
		var text = localStorage.getItem('$BankName') || "[]";
		var json = JSON.parse(text);
		if(code){ 
			json = json.filter(function(v, i){ return v.Code == code });
			return json.length > 0 ? json[0] : {};
		}
		else{
			return json;
		}
	};

	owner.setBankName = function(data) {
		data = data || [];
		localStorage.setItem('$BankName', JSON.stringify(data));
	};

	owner.getBankNameData = function(callback) {
		owner.post("GetBank", {}, function(data) {
			owner.setBankName(data);
			if(callback)
				callback(data);
		});
	};

	owner.getUserInfo = function() {
		return owner.getUser().User;
	};

	owner.setUserInfo = function(data) {
		data = data || [];
		var user = owner.getUser();
		user.User = data;
		owner.setUser(user);
	};
	
	owner.getAsset = function() {
		return owner.getUser().Asset;
	};

	owner.setAsset = function(data) {
		data = data || [];
		var user = owner.getUser();
		user.Asset = data;
		owner.setUser(user);
	};

	/**
	 * 支持银行
	 **/
	owner.getBanks = function() {
		return owner.getUser().Banks;
	};

	/**
	 * 刷新资金
	 **/
	owner.refreshAsset = function(callback) {
		owner.post("GetAsset", {
			Account: owner.account()
		}, function(data) {
			//console.log(JSON.stringify(data));
			owner.setAsset(data);
			if(callback) callback(data);
		});
	};

	owner.getAssetData = function(callback) {
		owner.post("GetAsset", {}, function(data) {
			owner.setAsset(data);
			if(callback)
				callback(data);
		});
	};

	owner.refreshUser = function(callback) {
		owner.post("GetUser", {}, function(data) {
			//console.log(JSON.stringify(data));
			owner.setUser(data.data);
			if(callback) callback(data.data);
		});
	};

	/**
	 * 获取用户数据
	 **/
	owner.getUser = function() {
		var userText = localStorage.getItem('$user') || "{}";
		return JSON.parse(userText);
	};

	/**
	 * 设置用户数据
	 **/
	owner.setUser = function(user) {
		user = user || {};
		localStorage.setItem('$user', JSON.stringify(user));
	};

	owner.account = function() {
		return owner.getState().account || "";
	};

	/**
	 * 用户是否已登录
	 **/
	owner.isLogin = function() {
		return owner.account() ? true : false;
	};

	/**
	 * 用户是否实名认证
	 **/
	owner.checkIDAuth = function() {
		console.log(owner.getUser().User.AuthenticationStatus);
		if(owner.getUser().User.AuthenticationStatus != 2) {
			mui.toast("请完成实名认证")
			mui.openWindow("profile-authentication.html", "profile-authentication");
			return false;
		}
		return true;
	};

	owner.createState = function(name, callback) {
		var state = owner.getState();
		state.account = name;
		state.token = "token123456789";
		owner.setState(state);
		return callback();
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
	};

	var checkEmail = function(email) {
		email = email || '';
		return(email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if(!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	owner.setMarketData = function(data) {
		data = data || [];
		localStorage.setItem('$markets', JSON.stringify(data));
	};

	owner.getMarketData = function(id) {
		var text = localStorage.getItem('$markets') || "[]";
		var json = JSON.parse(text);
		if(id) {
			var f = json.filter(function(item) {
				return item.GoodsID == id;
			});
			return f.length > 0 ? f[0] : null;
		} else {
			return json;
		}
	};

	owner.updateSettings = function(key, value) {
		var settings = owner.getSettings();
		settings[key] = value;
		owner.setSettings(settings);
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		var data = owner.getUser();
		data.Settings = settings;
		owner.setUser(data);
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		return owner.getUser().Settings || {};
	}

	/**
	 * 获取本地是否安装客户端
	 **/
	owner.isInstalled = function(id) {
		if(id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if(mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch(e) {}
		} else {
			switch(id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	};

	owner.getClientID = function() {
		var info = plus.push.getClientInfo();
		return info.clientid;
	};

	owner.getParam = function(name) {
		var uri = window.location.search.replace('?', '');
		var data = uri.split('&');
		var arr = new Array();
		if(data) {
			for(var i in data) {
				var tmp = data[i].split('=');
				if(tmp[0]) {
					arr[tmp[0]] = tmp[1];
				}
			}
		}
		return arr[name];
	};

	owner.getActiveTab = function(tabID) {
		var segmentedControl = document.getElementById(tabID);
		var links = segmentedControl.getElementsByTagName('a');
		for(var i = 0; i < links.length; i++) {
			if(links[i].getAttribute('class').indexOf('mui-active') > 0) {
				var id = links[i].getAttribute('href');
				return id;
			}
		}
	}

	owner.fmoney = function(s, c) {
		if(!s) return "0.00";
		var n = s,
			c = isNaN(c = Math.abs(c)) ? 2 : c,
			d = d == undefined ? "." : d,
			t = t == undefined ? "," : t,
			s = n < 0 ? "-" : "",
			i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
			j = (j = i.length) > 3 ? j % 3 : 0;
		return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "")
	}

	owner.getProfitSymbol = function(amount) {
		return amount == 0 ? "" : (amount > 0 ? "+" : "");
	}

	var $wvMessage;
	owner.openMessage = function(id) {
		if(!$wvMessage) {
			$wvMessage = plus.webview.getWebviewById("message-item");
		}

		$wvMessage.evalJS("show(" + id + ")");
		$wvMessage.show();
	}
}(mui, window.app = {}));

mui.ready(function() {
	mui(".nav-tab").on('tap', '.mui-tab-item', function() {
		//获取id
		var id = this.getAttribute("name");
		if(id == "navpay") {
			var launch = plus.webview.getLaunchWebview();
			launch.show();
		} else if(id) {
			var href = this.getAttribute("data-href");
			if(href) {
				mui.openWindow({
					id: id,
					url: href
				});
			} else {
				return false;
			}
		}
	});

	mui("body").on('tap', '.open-window', function() {
		console.log("tap");
		var url = this.getAttribute('data-url');
		var id = this.getAttribute('data-id') || url.split("?")[0];
		if(url) {
			var params = this.getAttribute('data-params');
			var urlparams = ''; 
			if(params) {
				console.log(JSON.stringify(params));
				var json = JSON.parse(params);
				for(var key in json) {
					urlparams += key + '=' + json[key] + '&';
				}
				url += '?' + urlparams.slice(0, urlparams.length-1);
				console.log(url);
			}
			mui.openWindow(url, id);
		}
		return false;
	});

	setTimeout(function() {
		mui("header").on('tap', '.mui-action-close', function() {
			plus.webview.currentWebview().close();
		});
	}, 1000);

	setTimeout(function() {
		mui("header").on('tap', '.mui-action-hide', function() {
			plus.webview.currentWebview().hide();
		});
	}, 1000);

});

/*
//两种调用方式
var template1 = "我是{0}，今年{1}了";
var template2 = "我是{name}，今年{age}了";
var result1 = template1.format("loogn", 22);
var result2 = template2.format({ name: "loogn", age: 22 });
//两个结果都是"我是loogn，今年22了"
*/
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

Date.prototype.format = function(format) {
	var o = {
		"M+": this.getMonth() + 1, //month 
		"d+": this.getDate(), //day 
		"h+": this.getHours(), //hour 
		"m+": this.getMinutes(), //minute 
		"s+": this.getSeconds(), //second 
		"q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
		"S": this.getMilliseconds() //millisecond 
	}

	if(/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}

	for(var k in o) {
		if(new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
}

function getUTCTime(time) {
	return new Date(new Date(new Date().getFullYear() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getDate() + " " + time).getTime() - new Date(1970, 0, 1, 0, 0, 0).getTime()).getTime()
}

function getUTCByDT(datetime) {
	return new Date(new Date(datetime).getTime() - new Date(1970, 0, 1, 0, 0, 0).getTime()).getTime()
}

function hasClass(obj, cls) {
	return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(obj, cls) {
	if(!this.hasClass(obj, cls)) {
		obj.className += " " + cls;
	}
}

function removeChildClass(obj, childName, className) {
	var elements = obj.getElementsByTagName(childName);
	for(var i = 0; i < elements.length; i++) {
		removeClass(elements[i], className);
	}
}

function removeClass(obj, cls) {
	if(hasClass(obj, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		obj.className = obj.className.replace(reg, ' ');
	}
}

function toggleClass(obj, cls) {
	if(hasClass(obj, cls)) {
		removeClass(obj, cls);
	} else {
		addClass(obj, cls);
	}
}

hideClass = function(className) {
	var elements = document.getElementsByClassName(className);
	for(var i = 0; i < elements.length; i++) {
		elements[i].style.display = "none";
	}
}

showClass = function(className) {
	var elements = document.getElementsByClassName(className);
	for(var i = 0; i < elements.length; i++) {
		elements[i].style.display = "block";
	}
}

hide = function(obj) {
	obj.style.display = "none";
}

show = function(obj) {
	obj.style.display = "block";
}

formatBankCardShow = function(obj) {
	return obj.BankAbbr + resources.GetBankCardTypeByValue(obj.Type) + ' ' + obj.CardNo.substr(obj.CardNo.length - 4);
}

formatBankCard = function(obj) {
	obj.value = obj.value.replace(/\s/g, '').replace(/[^\d]/g, '').replace(/(\d{4})(?=\d)/g, '$1 ');
}

var mobileLength = 0;
formatMobile = function(obj) {
	var phoneNum = obj.value.replace(/[^\d\s]/g, '');
	var len = phoneNum.length;
	if(len > mobileLength) {
		if(len === 4 || len === 9) {
			phoneNum = phoneNum.substr(0, phoneNum.length - 1) + ' ' + phoneNum[phoneNum.length - 1];
			obj.value = phoneNum;
		}
	}
	mobileLength = len;
}

formatCardDay = function(day) {
	return day < 10 ? "0" + day : day;
}

formatAmount = function (amount) {
	amount = amount.toFixed(2)+'';
	var integer = amount.substr(0,amount.indexOf("."));
	integer = integer == "" ? amount : integer;
	return amount.replace(integer, "<span class='mui-h4'>"+integer+"</span>");
}

$id = function(id) {
	return document.getElementById(id);
}

getKeyByValue = function(data, value) {
	for(var key in data) {
		if(data[key] == value) {
			return key;
		}
	};
}

openExternalLinks = function(title, url, id) {
	var $wv = mui.openWindowWithTitle({
		url: url,
		id: id,
		show: {
			event: "loaded",
		}
	}, {
		backgroundColor: "#ffffff", //导航栏背景色
		bottomBorderColor: "#eeeeee", //底部边线颜色
		title: {
			text: title
		},
		back: {
			image: {
				base64Data: ""
			}
		}
	});
	$wv.appendJsFile("js/mui.min.js");
}

var isSendAuthCode = false;
sendAuthCode = function(obj) {
	var mobile = $id("MobileNo").value.replace(/\s/g, "");
	if(isSendAuthCode) {
		return;
	}
	if(!checkMobile(mobile)) {
		return;
	}
	
	var type = obj.getAttribute("data-type");
	var check = obj.getAttribute("data-check");

	mui.showLoading();
	app.post("GetRegisterAuthCode", {
		MobileNo: mobile, Type:type, IsCheck:check
	}, function(data) {
		if(data.isSuccess) {
			mui.toast("短信已发送，请注意查收");
			
			var waitTime = 60;
			var waitLoop = setInterval(function() {
				isSendAuthCode = true;
				obj.innerText = waitTime + " 秒后重发";
				if(waitTime == 0) {
					isSendAuthCode = false;
					clearInterval(waitLoop);
					obj.innerText = "发送验证码";
				}
				waitTime--;
			}, 1000);
		} else {
			mui.toast(data.message);
		}
	})
}

checkMobile = function(mobile) {
	if(mobile == "") {
		mui.toast("请输入手机号");
		return false;
	}

	var reg = /^1[0-9]{10}$/;
	if(!reg.test(mobile)) {
		mui.toast("请输入正确的手机号");
		return false;
	}

	return true;
}

var $btnSendAuthCode = document.getElementById("btnSendAuthCode");
$btnSendAuthCode && $btnSendAuthCode.addEventListener('tap', function() {
	sendAuthCode(this);
});